using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Globalization;

/// 22.02.2009 - adaugare cautare cu FindRows
/// 
namespace ERPStudio
{
    public partial class FrmSearch : FrmRezumat
    {

        /// <summary>
        /// clasa functioneaza pentru cautarea intr-o singura tabele
        /// </summary>
        private DataRowView[] setRowSelected = null;
        private BindingSource pozitionator = null;
        private SqlConnection sqlConn = null;
        public int cata = 0;

        public FrmSearch(/*DataTable plistDT,*/ BindingSource bs, SqlConnection vsqlComm,ModuleClass mInfo) : base(mInfo)
        {
            InitializeComponent();
            pozitionator = bs;
            sqlConn = vsqlComm;
            AddRows();
            HandleSalvare += new EventHandler(Cauta);
        }

        public void AddRows()
        {
            
            DataView dv = ((DataView)pozitionator.List);
            SqlCommand cmd = new SqlCommand("SELECT * FROM [TabelaCampuriCauta] WHERE [Vizibila]=1 AND [NumeTabela]='" + dv.Table.TableName + "' ORDER BY [Pozitie]", sqlConn);
            SqlDataReader rd = cmd.ExecuteReader();
            if (rd == null)
                return;
            Int16 i = 0;
            while (rd.Read())
            {
                this.dataGrid1.Rows.Add();
                DataColumn dc = GetColumnInfo(rd["NumeCamp"].ToString());
                if (dc != null)
                {
                    //FORMATEAZA CELULA
                    if (dc.DataType == typeof(DateTime))
                    {
                        RelationTextBox.DataGridViewMaskedTextCell mtb = new RelationTextBox.DataGridViewMaskedTextCell();
                        this.dataGrid1.Rows[i].Cells[1] = mtb;
                        mtb.Mask = "00/00/0000-00/00/0000";
                    }
                }

                this.dataGrid1.Rows[i].Cells[0].Value = rd["Denumire"].ToString();
                this.dataGrid1.Rows[i].Cells[0].Tag = rd["NumeCamp"].ToString();
                i++;
            }
                       
            if (this.dataGrid1.Rows.Count > 0 && this.dataGrid1.Rows[0].Cells.Count > 0)
                this.dataGrid1.Rows[0].Cells[1].Selected = true;
            rd.Close();
            rd.Dispose();
        }

        new private void Cauta(object sender, EventArgs e)
        {
            cata = 1; //initializeaza contorul pentru cautarile 
            //urmatoare
            DataView dv = ((DataView)pozitionator.List);
            dv.Sort = BuildSort();
            if (dv.Sort == String.Empty)
            {
                MessageBox.Show("Nu ati specificat nici un criteriu de cautare!", "Atentionare", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                dv.ApplyDefaultSort = true;
                return;
            }
            //dv.RowFilter = BuildFilter();
            Cursor.Current = Cursors.AppStarting;
            Object[] ret = BuildSortValue();
            if(ret.Length!=0)
                setRowSelected = dv.FindRows(ret);
            Cursor.Current = Cursors.Default;
            if (setRowSelected==null || setRowSelected.Length == 0)
            {
                MessageBox.Show("Element inexistent! Va rugam simplificati cautarea!", "Cauta", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            pozitionator.Position = pozitionator.IndexOf(setRowSelected[0]);
        }

        private void Filtreaza(object sender, EventArgs e)
        {
            cata = 1; //initializeaza contorul pentru cautarile 
            //urmatoare
            DataView dv = ((DataView)pozitionator.List);
            dv.RowFilter = BuildFilter();
            SetStatus(dv.RowFilter);
        }

        private DataColumn GetColumnInfo(String numeColoana)
        {
            DataView dv = ((DataView)pozitionator.List);
            DataColumn dc = null;
            foreach (DataColumn dc1 in dv.Table.Columns)
                if (dc1.ColumnName == numeColoana)
                {
                    dc = dc1;
                    break;
                }
            return dc;
        }
        /// <summary>
        /// pe baza datelor introduse de utilizator construieste filtrul
        /// </summary>
        /// <returns></returns>
        public String BuildFilter()
        {
            StringBuilder filtru = new StringBuilder();
            DataView dv = ((DataView)pozitionator.List);
            Int16 i = 0;
            foreach (DataGridViewRow dr in dataGrid1.Rows)
            {
                //pentru fiecare rand in care scrie ceva
                if (dr.Cells[1].EditedFormattedValue  != null &&
                    dr.Cells[1].EditedFormattedValue.ToString() != String.Empty)
                {
                    DataColumn dc = null;
                    foreach (DataColumn dc1 in dv.Table.Columns)
                        if (dc1.ColumnName == dr.Cells[0].Tag.ToString())
                        {
                            dc = dc1;
                            break;
                        }

                    if(dc==null)
                        continue;

                    
                    
                    //in prima coloana se afla numele campului



                    if (dc.DataType == typeof(DateTime))
                    {
                        ///daca este de tip data permitem si un interval
                        Match m1 = Regex.Match(dataGrid1.Rows[i].Cells[1].EditedFormattedValue.ToString()
                            , @"(?<datastart>[\s|\d|\\|\.]+)-(?<dataend>[\s|\d|\\|\.]+)");
                        if (m1.Success == true)
                        {
                            //ctrlServer.Text = m1.Groups["datasource"].ToString();
                            CultureInfo provider = CultureInfo.CurrentCulture;
                            DateTime dtStart = DateTime.MinValue;
                            DateTime dtEnd = DateTime.MaxValue;
                            try
                            {
                                dtStart = DateTime.Parse(m1.Groups["datastart"].ToString(), provider);
                            }
                            catch (Exception) { }
                            try
                            {
                                dtEnd = DateTime.Parse(m1.Groups["dataend"].ToString(), provider);
                            }
                            catch (Exception) { }

                            if (dtStart != DateTime.MinValue && dtEnd == DateTime.MaxValue)
                            {
                                if (filtru.Length > 0)
                                    filtru.Append(" OR ");

                                filtru.Append("[" + dc.ColumnName + "]");
                                filtru.Append(" >= '" + dtStart.Year.ToString() + "-" + dtStart.Month.ToString() + "-" + dtStart.Day.ToString() + "'");
                            }
                            else
                                if (dtStart == DateTime.MinValue && dtEnd != DateTime.MaxValue)
                                {
                                    if (filtru.Length > 0)
                                        filtru.Append(" OR ");
                                    filtru.Append("[" + dc.ColumnName + "]");
                                    filtru.Append(" <= '" + dtEnd.Year.ToString() + "-" + dtEnd.Month.ToString() + "-" + dtEnd.Day.ToString() + "'");
                                }
                                else
                                    if (dtStart != DateTime.MinValue && dtEnd != DateTime.MaxValue)
                                    {
                                        if (filtru.Length > 0)
                                            filtru.Append(" OR ");
                                        filtru.Append("[" + dc.ColumnName + "]");
                                        filtru.Append(" >= '" + dtStart.Year.ToString() + "-" + dtStart.Month.ToString() + "-" + dtStart.Day.ToString() + "' AND ");
                                        filtru.Append("[" + dc.ColumnName + "]");
                                        filtru.Append(" <= '" + dtEnd.Year.ToString() + "-" + dtEnd.Month.ToString() + "-" + dtEnd.Day.ToString() + "'");
                                    }


                        }
                        else
                        {
                            MessageBox.Show("Format incorect pentru filtru!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                            return String.Empty;
                        }


                    }
                    else
                    {
                        if (filtru.Length > 0)
                            filtru.Append(" OR ");

                        if (dc.DataType == typeof(String) || dc.DataType == typeof(Char))
                        {
                            filtru.Append("[" + dc.ColumnName + "]");
                            filtru.Append(" like \'");
                            filtru.Append(dataGrid1.Rows[i].Cells[1].EditedFormattedValue.ToString());
                            filtru.Append("%\'");
                        }
                        else
                        {
                            filtru.Append("[" + dc.ColumnName + "]");
                            filtru.Append("=");
                            filtru.Append(dataGrid1.Rows[i].Cells[1].EditedFormattedValue.ToString());
                        }
                    }

                    
                }
                i++;
            }
            return filtru.ToString();
        }
        /// <summary>
        /// returneaza coloanele dupa care va fi sortat
        /// </summary>
        /// <returns></returns>
        public String BuildSort()
        {
            StringBuilder sort = new StringBuilder();
            DataView dv = ((DataView)pozitionator.List);
            Int16 i = 0;
            foreach (DataGridViewRow dr in dataGrid1.Rows)
            {
                //pentru fiecare rand in care scrie ceva
                if (dr.Cells[1].EditedFormattedValue != null &&
                    dr.Cells[1].EditedFormattedValue.ToString() != String.Empty)
                {
                    if (sort.Length > 0)
                        sort.Append(",");

                    sort.Append("[" + dr.Cells[0].Tag.ToString() + "]");
                }
                i++;
            }
            return sort.ToString();
        }

        public Object[] BuildSortValue()
        {
            List<Object> rez = new List<Object>();
            DataView dv = ((DataView)pozitionator.List);
            Int16 i = 0;
            foreach (DataGridViewRow dr in dataGrid1.Rows)
            {
                //pentru fiecare rand in care scrie ceva
                if (dataGrid1.Rows[i].Cells[1].EditedFormattedValue != null &&
                    dataGrid1.Rows[i].Cells[1].EditedFormattedValue.ToString() != String.Empty)
                {
                    rez.Add(dataGrid1.Rows[i].Cells[1].EditedFormattedValue);
                }
                i++;
            }
            return rez.ToArray();
        
        }

        private void FrmSearch_Load(object sender, EventArgs e)
        {
            AddButton("Cauta", global::ERPStudio.Properties.Resources.find, Cauta, ToolStripItemAlignment.Right,true);
            AddButton("Filtreaza", global::ERPStudio.Properties.Resources.table_48, Filtreaza, ToolStripItemAlignment.Right,false);
            dataGrid1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
            dataGrid1.Columns["Valoare"].Width = 200;
        }
    }
}